package com.george.auth.service.excel.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.george.auth.component.application.ApplicationContextHandle;
import com.george.auth.dto.excel.StCActivityRefundDiffStrategyExcelData;
import com.george.auth.service.excel.StCActivityRefundDiffStrategyImportExportService;
import com.george.common.entity.dto.Result;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @title: StCActivityRefundDiffStrategyImportExportServiceImpl.java
 * @description:
 * @author: George.Dong
 * @date: 2024/3/5 15:05
 */
@Service
@Slf4j
public class StCActivityRefundDiffStrategyImportExportServiceImpl implements StCActivityRefundDiffStrategyImportExportService {
    /**
     * 按明细导出
     *
     * @param jsonObject JSON对象
     * @return {@link Result}
     */
    @Override
    public ResponseEntity<Object> exportByItem(JSONObject jsonObject, HttpServletResponse response) {
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            // 模拟数据
            List<StCActivityRefundDiffStrategyExcelData> dataList = new ArrayList<>();
            for (int i = 0; i < 100; i++) {
                StCActivityRefundDiffStrategyExcelData data = new StCActivityRefundDiffStrategyExcelData();
                data.setActivityType(String.valueOf(i + 1));
                data.setCpCShopId(String.valueOf(i + 1));
                dataList.add(data);
            }
            byteArrayOutputStream = new ByteArrayOutputStream();
            HorizontalCellStyleStrategy cellStyleStrategy = ApplicationContextHandle.getBean("R3StHorizontalCellStyleStrategy");
            //excel操作器,不允许自动关闭文件流（防止频繁开关），外层手动关闭
            ExcelWriter excelWriter = EasyExcelFactory.write(byteArrayOutputStream, StCActivityRefundDiffStrategyExcelData.class)
                    .autoCloseStream(Boolean.FALSE)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .registerWriteHandler(cellStyleStrategy)//设置字体样式
                    .excelType(ExcelTypeEnum.XLSX).build();
            //写入磁盘
            excelWriter.write(dataList, EasyExcelFactory
                    .writerSheet(0, "Sheet1")
                    .build());
            //清理大对象
            dataList.clear();
            excelWriter.finish();

            byte[] excelBytes = byteArrayOutputStream.toByteArray();
            // 直接设置Http响应头并返回字节数组
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=export_" + System.currentTimeMillis() + ".xlsx");
            return ResponseEntity.ok(excelBytes);
        } catch (Exception ex) {
            log.error("StCActivityRefundDiffStrategyImportExportCmdImpl-exportByItem,执行异常:{}", Throwables.getStackTraceAsString(ex));
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导出异常，异常原因：" + ex.getMessage());
        } finally {
            if (null != byteArrayOutputStream) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    log.error("StCActivityRefundDiffStrategyImportExportCmdImpl-exportByItem,关闭流异常:{}", Throwables.getStackTraceAsString(e));
                }
            }
        }
    }

    @Bean(name = "R3StHorizontalCellStyleStrategy")
    public HorizontalCellStyleStrategy r3StHorizontalCellStyleStrategy() {
        //标题样式
        WriteCellStyle titleStyle = new WriteCellStyle();
        WriteFont titleFont = new WriteFont();
        titleFont.setFontHeightInPoints((short) 10);
        titleFont.setFontName("宋体");
        titleFont.setColor(IndexedColors.DARK_BLUE.index);
        titleFont.setBold(true);
        titleStyle.setWriteFont(titleFont);

        //内容样式
        WriteCellStyle style = new WriteCellStyle();
        WriteFont font = new WriteFont();
        font.setFontHeightInPoints((short) 10);
        font.setFontName("宋体");
        style.setWriteFont(font);
        style.setWrapped(true);

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        return new HorizontalCellStyleStrategy(titleStyle, style);
    }
}
